
const path = require("path");

const targetUrl = 'http://192.168.0.66:30000';

const resolve = (dir) => path.join(__dirname, dir);

/**
 * 获取代理信息
 * @param path 指定代理地址，默认测试环境
 */
function getProxyInfo(path = '') {
  return {
    target: path || targetUrl,
    changeOrigin: true,
    pathRewrite: {
      '^/api': '/'
    },
    /** 
     * webpack跨域配置! 不配会报下面错误
     * 'http://localhost:2335/api/xxx/xxx' from origin 'http://localhost:2666' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
     */
    onProxyRes: function (proxyRes, req, res) {
      if (req.method === 'OPTIONS') {
        proxyRes.headers['Access-Control-Allow-Origin'] = req.headers.origin || '*'
        proxyRes.headers['Access-Control-Allow-Credentials'] = true
        proxyRes.headers['Access-Control-Allow-Methods'] = 'GET,POST,OPTIONS,PUT,DELETE,FETCH'
        /** 
         * 这里的参数，根据自己项目增删, 配置不对会报下面错误
         * Request header field codemode is not allowed by Access-Control-Allow-Headers in preflight response
         */
        proxyRes.headers['Access-Control-Allow-Headers'] = 'authorization,businesscentermenuid,codemode,content-type,kch-userid,kch-username'
        proxyRes.statusCode = 204
      } else {
        proxyRes.headers['Access-Control-Allow-Origin'] = req.headers.origin || '*'
        proxyRes.headers['Access-Control-Allow-Credentials'] = true
      }
    },
  }
}

module.exports = {
  // outputDir: 'dist',
  publicPath: '/microappC/', // 相当于vite的base
  devServer: {
    /** 
     * 不检查Host
     * 否则webpack本地*.ifuhua.com.cn打开会报Invalid Host header
     */
    disableHostCheck: true,
    hot: false,
    port: 2335,
    open: false,
    headers: {
      'Access-Control-Allow-Origin': '*',
    },
    proxy: {
      '/api': getProxyInfo(),
    },
  },
  // 自定义webpack配置
  configureWebpack: {

  },
  chainWebpack(config) {
    // set svg-sprite-loader
    config.module.rule("svg").exclude.add(resolve("./src/icons")).end();
    config.module
      .rule("icons")
      .test(/\.svg$/)
      .include.add(resolve("src/icons"))
      .end()
      .use("svg-sprite-loader")
      .loader("svg-sprite-loader")
      .options({
        symbolId: "icon-[name]",
      })
      .end();
  },
}
